import { downloadFile } from '@/utils/file'
import type { PDFDocumentProxy } from 'pdfjs-dist'
import { ref, unref } from 'vue'

export const usePdf2Text = () => {
  const text = ref('')

  // 解析pdf
  const parsePDF = async () => {}

  // 转换pdf
  const transferPDF2Text = async (pdf: PDFDocumentProxy) => {
    text.value = ''
    const numPages = pdf.numPages
    for (let i = 1; i <= numPages; i++) {
      const page = await pdf.getPage(i)
      const textContent = await page.getTextContent()
      text.value +=
        textContent.items
          .map((item: RecordRaw) => (item.str?.length ? item.str : '\r\n'))
          .toString() + '\r\n'
    }
  }

  // 保存文本
  const saveText = (fileName: string) => {
    let content = encodeURIComponent(unref(text))
    downloadFile(`data:text/plain;charset=utf-8,${content}`, fileName)
  }

  return {
    parsePDF,
    transferPDF2Text,
    saveText,
  }
}
